import PGS from "@src/pages";
import * as R from "ramda";
import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
import { useRouterStateStore } from "./state";
import publicStore from "@src/stores";

const router = createRouter({
  history: import.meta.env.VITE_APP_ROUTE_HISTORY_MODE =='hash'? createWebHashHistory(): createWebHistory(import.meta.env.VITE_APP_SITE_BASE_ROUTER||'/'),
  routes:[
    R.mergeAll([PGS.MainPg,{children:[
      PGS.DashboardPg,
      PGS.ThemePg,
    ]}]),
    PGS.LoginPg,
    PGS.Erro403Pg,
    PGS.Erro404Pg,
  ],
});
router.beforeEach(async (to, from, next ) => {
  try{
    const proxy = publicStore.useAppStateStore().getRootInstance; // 获取根节点的vue实例，方便在跳转时，对意外情况，进行弹窗等处理;
    // const { preventStore } = usePreventBrowserBehavior();
    const result = useRouterStateStore().getPreventNavigation ? await proxy.$confirm(useRouterStateStore().getPreventDialogContent) : 'confirm';
    if(result == 'confirm'){
      // if ( to.meta.onlyWS &&  !store.getters.screen.isWS) {
      //   return { name: 'erroDev' };
      // }
      // 1.如果匹配不上的页面，则直接404
      // console.log(from)
      if (to.matched.length == 0) {
        next({ name: 'erro-404' });
        return;
      };
      // 2.如果路由包含登录验证，则需通过登录检测，否则直接转登录页面
      if (to.meta.tokenRequire) { //需要token校验时
        const userStore = publicStore.useUserBaseStateStore(); // 取出token
        if (R.isNil(userStore.getToken.access_token)) { //token为空或为null值时
          console.warn('尚未登录，现返回登录页面...');
          next({ name:'login-pg' });
          return;
        }
      };
      // //2.检测路由访问权限,如有权限约束，但用户未获得权限，则会直接跳转至403
      if (!R.isEmpty(to.meta.powerRequire) && !R.isNil(to.meta.powerRequire)) { //路由配置信息的权限需求不为空且不为null值时
        const userInfo = publicStore.useUserBaseStateStore().getInfo; // 取出user状态
        if (R.intersection(userInfo.power||[], to.meta.powerRequire as readonly (string|number)[]).length < 1) { //权限交集长度<1时，即用户权限点不满路由配置条件
          console.warn('用户权限不符，该页面禁止访问。')
          next({ name:'erro-403' });
        }
      };
      if (!R.isNil(to) && !R.isEmpty(to)) { //当to不为空与null时
        to.meta?.keepAlive ? useRouterStateStore().insertKeepAlivePage(to.name as string) : useRouterStateStore().removeKeepAlivePage(to.name as string)
      };
      // if(!to.meta.avoidTag){ // 如果该页面 meta 配置中 avoidTag 为 false 时，则会塞入新的标签菜单
      //   store.commit('menu/tagInsert',{ label:to.meta.title, value:to.name, static:to.meta.static, to:R.pick([
      //     'fullPath','hash','href','meta','name','params','path','query',
      //   ],to)});
      // }
      next();
  }else{
    next(false);
  };
  }catch(err){
    console.log(err);
    next(false);
  }
});
router.afterEach((to)=>{
  // 路由后置守卫钩子，用于路由分析等
})
router.onError((err)=>{
  console.log(err)
});

export default router;